#include "morsecodeplugin.h"

MorseCodePlugin::MorseCodePlugin()
{
    m_settingsFile = new QSettings("morsecodeplugin.ini", QSettings::IniFormat);
    constructSettings();
    constructBlinkSequence();

    m_timer = new QTimer(this);
    m_timer->setSingleShot(true);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(blink()));
}

MorseCodePlugin::~MorseCodePlugin()
{
    delete m_settingsFile;
    delete m_timer;
}

QString MorseCodePlugin::name()
{
    return "Morse Code Plugin";
}

QList<PluginInterface::Setting> MorseCodePlugin::settings()
{
    return m_settings;
}

void MorseCodePlugin::updateSetting(QString name, QVariant value)
{
    if( name == "Morse code string" )
    {
        m_settings[0].value = value;
        m_settingsFile->setValue("morsecodestring", value);
        constructBlinkSequence();
    }
    else if( name == "Interval" )
    {
        m_settings[1].value = value;
        m_settingsFile->setValue("interval", value);
    }
}

QString MorseCodePlugin::version()
{
    return VERSION;
}

void MorseCodePlugin::setEnabled(bool enabled)
{
    if( enabled )
        m_timer->start(m_settings[1].value.toInt());
    else
        m_timer->stop();
}

void MorseCodePlugin::constructSettings()
{
    Setting morsecodestring;
    morsecodestring.name = "Morse code string";
    morsecodestring.type = PluginInterface::TEXT;
    morsecodestring.value = m_settingsFile->value("morsecodestring", "SOS");
    m_settings.append(morsecodestring);

    Setting interval;
    interval.name = "Interval";
    interval.type = PluginInterface::TEXT;
    interval.value = m_settingsFile->value("interval", 5*60*1000);
    m_settings.append(interval);
}

void MorseCodePlugin::constructBlinkSequence()
{
    m_blinkSequence = StringToBlinkSequence::convert(m_settings.at(0).value.toString());
}

void MorseCodePlugin::blink()
{
    emit blinkReady(m_blinkSequence);
    m_timer->start(m_settings[1].value.toInt());
}

Q_EXPORT_PLUGIN2(morsecodeplugin, MorseCodePlugin)
